const fs = require('fs');
const path = require('path');
const md5 = require('md5');
class UplocadImg {
    async uploadPicture(ctx) {   //图片上传
        const { url = "" } = ctx.query;
        const file = ctx.request.files.file; // 获取上传文件
        if (file.size < 1024 * 1024 * 2 && file.type == 'image/jpeg') {
            const fileUrl = path.join(__dirname, '../../public/picture/', url, '/');
            if (!fs.existsSync(fileUrl)) {
                fs.mkdirSync(fileUrl);
            }
            // 创建可读流
            const reader = fs.createReadStream(file.path);
            const fileName = md5(ctx.state.user.username + new Date().getTime()) + file.name.substr(file.name.lastIndexOf('.'));
            const filePath = path.join(__dirname, '../../public/picture/', url, '/') + fileName;
            // 创建可写流
            const upStream = fs.createWriteStream(filePath);
            // 可读流通过管道写入可写流
            reader.pipe(upStream);
            // const urls = 'http://localhost:3000/picture/' + url + '/' + fileName;
            const urls = '/picture/' + url + '/' + fileName;
            await ctx.app.Service.User.update({ avatar: urls }, {
                where: {
                    id: ctx.state.user.id
                }
            })
            ctx.body = {
                code: 200,
                message: '成功',
                url: urls
            }
        } else {
            ctx.body = {
                code: 201,
                message: '请上传小于2M的jpg格式图片！'
            }
        }
    }
}
module.exports = UplocadImg;